<?php

declare(strict_types=1);

namespace App\Models;

use DB;
use Illuminate\Database\Eloquent\Model;

class HomepageRecommend extends Model
{
    public $timestamps = false;

    protected $table = 'homepage_recommend';

    public static function getCityRecommend($cityId = 0, $withoutHidden = true, $sortBy = '')
    {
        // DB::connection()->enableQueryLog();
        $query =
        self::select('*')->
        where(function ($query) use ($cityId) {
            $query->where(function ($query) use ($cityId) {
                $query->
                whereIn('product_id', function ($query) use ($cityId) {
                    $query->from('product_ranges')->where(['area_code' => $cityId, 'area_level' => 1])->select('product_id')->get();
                })->
                where(function ($query) use ($cityId) {
                    $query->where(['city_id' => 0])->orWhere(['city_id' => $cityId]);
                });
            })->
            orWhere(function ($query) use ($cityId) {
                $query->where(['product_id' => 0, ['link_url', '<>', '']])->
                where(function ($query) use ($cityId) {
                    $query->where(['city_id' => 0])->orWhere(['city_id' => $cityId]);
                });
            });
        });
        if ($sortBy) {
            [$sortCol, $sortDirect] = explode(',', $sortBy);
            $query->orderBy($sortCol, $sortDirect);
        } else {
            $query->orderBy('sort_weight', 'desc');
        }
        if ($withoutHidden) {
            $query->where(['hidden' => 0]);
        }

        return $query->get();
    }
}
